package com.ld.security.common.quartz.modules.job.service.impl;


import com.ld.security.common.core.base.column.MapJson;
import com.ld.security.common.core.base.po.SuperPo;
import com.ld.security.common.mybatis.base.service.ISuperServiceImpl;
import com.ld.security.common.quartz.modules.job.constant.JobTaskConstant;
import com.ld.security.common.quartz.modules.job.entity.JobTask;
import com.ld.security.common.quartz.modules.job.service.IJobTaskService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

@Service
@Slf4j
class JobTaskServiceImpl extends ISuperServiceImpl<JobTask> implements IJobTaskService {


    @Autowired
    QuartzManager quartzManager;



    /**
     * 新增任务
     *
     * @param quartz
     * @return
     * @throws Exception
     */
    @SneakyThrows
    @Override
    public int save(JobTask quartz) {
        if(quartz.getDataMap() == null){
            quartz.setDataMap(new MapJson());
        }
        int total = super.save(quartz);
        switch (quartz.getJobStatus()){
            case run:{
                Class cls = Class.forName(quartz.getJobClassName());
                quartzManager.addOrUpdateJob(cls,quartz.getJobName(),quartz.getJobGroup(),quartz.getCronExpression(),quartz.getDataMap());
                break;
            }case await:{
                quartzManager.deleteJob(quartz.getJobName(),quartz.getJobGroup());
                break;
            }
        }
        return total;
    }

    /**
     * 任务删除
     * @param query
     * @return
     */
    @Override
    public int remove(SuperPo query) {

        List<JobTask> taskList =  this.all(query);
        for (JobTask qrtzTask : taskList) {
            quartzManager.deleteJob(qrtzTask.getJobName(),qrtzTask.getJobGroup());
        }
        return super.remove(query);
    }


    @Value("${spring.application.name}")
    private String appName ;

    /**
     * 任务批量启动
     */
    @PostConstruct
    public void run(){
        JobTask q = this.newInstance();
        q.setAppName(appName);
        q.setJobStatus(JobTaskConstant.jobStatus.run);
        List<JobTask> taskList =  this.all(q);
        for (JobTask qrtzTask : taskList) {
            quartzManager.runAJobNow(qrtzTask.getJobName(),qrtzTask.getJobGroup());
        }
    }


}